<?php

namespace app\admin\controller\short;

use app\admin\model\short\Thrid;
use app\common\controller\Backend;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Exception;
/**
 * 短连接管理
 *
 * @icon fa fa-circle-o
 */
class Shorturl extends Backend
{

    /**
     * Shorturl模型对象
     * @var \app\admin\model\short\Shorturl
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\short\Shorturl;

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    
    /**
     * 生成短连接
     */
    public function generate(){
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            $$this->getrandmax(8);
        }
    }

    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            //$result = $this->model->allowField(true)->save($params);
           
            $dirabc = $this->getrandmax(8);
            $dir123 = rand(0,9);
            
            //当文件夹（短链接）存在时 增加一位
            if(!is_dir($dirabc)){
                $shortdir = $dirabc;
            } else {
                $shortdir = $dirabc.$dir123;
            }
            $this->request->filter(['strip_tags', 'trim']);
            $dirpath = dirname($_SERVER['PHP_SELF']);
            $rootpath = dirname($_SERVER['PHP_SELF'])."/";
            if ($dirpath == "/"){$rootpath = "/";}
            $gen = $_SERVER['DOCUMENT_ROOT'];
            
            $originData = Thrid::where(['switch'=>1])->field('id,title,url')->select();
            $rand = array_rand($originData);
            
            $origin = $originData[$rand]['url'];
            $fixedDomains  = [
                'y1vk9zlep2.name',
                '9qrv29zd2.top'  ,
                '9cpzltef.biz'   ,
                'h9zzqforb.xyz'  ,
                'sna80fryju.info',
                'fastadmin.test'
                
            ];
            if (strlen($origin) > 10 && strpos($origin, strval("http"))!==false && !is_dir($shortdir)){
               
                $domains = [];
                $count = $params['num'] + 0;

                for ($i = 1; $i <= $count; $i++) {
                    $index = rand(0, count($fixedDomains) - 1); // 随机获取一个固定域名的索引
                    $domain = $fixedDomains[$index]; // 获取对应索引的固定域名
                    $param =  $shortdir. $i; // 参数可以根据需求自定义
                    $url = "http://".$domain.'/s/' . $param;
                    $domains[] = $url;
                    $origin = $originData[$rand]['url'];
                    
                    $data = [
                        'short_url'         => $url,
                        'short_param'       => $param,
                         'createtime'        => time()
                     ];
                     //$result = $this->model->allowField(true)->save($data);
                     $res = db('shorturl')->insertGetId($data);
                    
                    mkdir(iconv("UTF-8", "GBK", $gen.'/s/'.$param),0755,true);
                    $filename = $gen .'/s/'.$param."/index.html";
                    file_put_contents($filename, '<script type="text/javascript">location.href="'.$origin.'"</script>');
                }
                
                
                // $info = '<p>原来的 URL：<br/><a href="'.$origin.'" target="_blank">'.$origin.'</a></p>'
                //  .'<p>缩短的 URL：<br/><a href="'.$shortened.'" target="_blank">'.$shortened.'</a></p>';
                // $this->assign('info',$info);
                Db::commit();
                $this->success('成功');
            } else {
                // $info = "<p><b>您输入的URL无效！</b></p>";
                // $this->assign('info',$info);
                $this->error('错误');
            }
            
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        
    }

   public function getrandmax($num=6)
   {

    $letter_all = range('A', 'Z');
    shuffle($letter_all);
    //排除I、O字母
    $letter_array = array_diff($letter_all, ['I', 'O', 'D']);
   
    $num_array = range('0', '9');
    shuffle($num_array);

    $pattern = array_merge($num_array, $letter_array, $num_array);
    shuffle($pattern);
    $pattern = array_values($pattern);

    $code = '';
    for ($i = 0; $i < $num; $i++) {
        $code .= $pattern[mt_rand(0, count($pattern) - 1)];
    }
    $code = strtoupper($code);
  
    $check = Db::name('shorturl')->where('short_param', $code)->find();
    if ($check) {
        return $this->getrandmax();
    }
   
    return $code;
}



}
